package com.ailot.cloud.upms.api.datasource;


import com.baomidou.dynamic.datasource.provider.AbstractJdbcDataSourceProvider;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DataSourceProperty;
import com.google.common.collect.Maps;
import org.springframework.stereotype.Component;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Map;

/**
 * mysql动态数据源配置
 *
 * @Author : litao
 * @create 2023/12/7 10:06
 */

@Component
public class MysqlDynamicDataSourceProvider extends AbstractJdbcDataSourceProvider {

    private final DruidDataSourceProperties druidDataSourceProperties;

    public MysqlDynamicDataSourceProvider(DruidDataSourceProperties druidDataSourceProperties) {
        super(druidDataSourceProperties.getDriverClassName(), druidDataSourceProperties.getUrl(), druidDataSourceProperties.getUsername(), druidDataSourceProperties.getPassword());
        this.druidDataSourceProperties = druidDataSourceProperties;
    }

    @Override
    protected Map<String, DataSourceProperty> executeStmt(Statement statement) throws SQLException {
        ResultSet resultSet = statement.executeQuery(DataSourceConstant.DB_QUERY);
        Map<String, DataSourceProperty> dsMap = Maps.newHashMap();
        DataSourceProperty dataSourceProperty = new DataSourceProperty();
        dataSourceProperty.setDriverClassName(druidDataSourceProperties.getDriverClassName());
        dataSourceProperty.setUsername(druidDataSourceProperties.getUsername());
        dataSourceProperty.setPassword(druidDataSourceProperties.getPassword());
        dataSourceProperty.setUrl(druidDataSourceProperties.getUrl());
        dsMap.put(DataSourceConstant.DB_DEFAULT, dataSourceProperty);
        while (resultSet.next()) {
            String name = resultSet.getString(DataSourceConstant.DB_NAME);
            String username = resultSet.getString(DataSourceConstant.DB_USERNAME);
            String password = resultSet.getString(DataSourceConstant.DB_PASSWORD);
            String url = resultSet.getString(DataSourceConstant.DB_URL);
            DataSourceProperty dsp = new DataSourceProperty();
            dsp.setUsername(username);
            dsp.setPassword(password);
            dsp.setUrl(url);
            dsMap.put(name, dsp);
        }
        return dsMap;
    }


}
